﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Framework.Library.Base.Base;
using Framework.Library.Data.DAL.JObject;
using ServiceStack.Text;
using Framework.Library.Base.Helper;
using Framework.Library.Core.Utils.GlobalHelper;
using Framework.Library.Data.DAO;
using Framework.Library.Core.Utils.Security;
using Framework.Library.Data.DAL;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Config;
using Framework.Library.Core.Provider.Payment;

namespace Framework.Portal
{
    public partial class Default : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Configurations.AUTHENTICATION_MODE)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["code"]))
                {
                    if (!Session.IsOnline())
                    {
                        VcoinService vcoin = new VcoinService();
                        //Xử lý đoạn code nhận được
                        string _code = Request.QueryString["code"];
                        KeyAccess info = vcoin.GetAccess_token(_code);
                        if (info != null)
                        {
                            Context.Session.SetPrincipal(new Principal()
                            {
                                AccountId = Convert.ToInt64(info.UserId),
                                Username = info.User,
                                LastAction =
                                    DateTime.Now.AddMilliseconds(-5).Ticks,
                                Code = info.code,
                                AccessToken = info.access_token,
                                ExpriseTime = info.expires
                            });
                            if (Session["returnUrl"] != null)
                            {
                                string returnURL = Session["returnUrl"].ToString();
                                Session.Remove("returnUrl");
                                Response.Redirect(returnURL);
                            }
                        }
                    }
                }
            }
            LoadContent();
        }

        private void LoadContent()
        {
            //Xử lý load content theo template
            int menuId;
            int.TryParse(HttpContext.Current.Request.QueryString["m"], out menuId);
            int portalId = Configurations.PORTALID;
            int menutypeId;
            int.TryParse(HttpContext.Current.Request.QueryString["t"], out menutypeId);

            if (portalId == 0) portalId = Configurations.PORTALID;
            var infoPortal = Session.CurrentPortal(portalId);
            if (infoPortal == null)
            {
                infoPortal = ManagerFactory.DAOEntity.GetInfo(new PortalPortal() { PORTALID = portalId });
                Session.Add(cfg.PrefixMember.VALUE + "CURRENT_PORTAL_" + portalId, infoPortal);
            }
            if (infoPortal != null)
            {
                if (infoPortal.SA > 0)
                {
                    if (!CredentialHelper.IsValidCredential(HttpContext.Current.Request.UserHostAddress))
                        RedirectHelper.ErrorRedirect("Địa chỉ IP của bạn \"" + HttpContext.Current.Request.UserHostAddress + "\" đã bị chặn !");
                }
                var infoMenu = ManagerFactory.PortalMenuManager.GetInfo(portalId, menuId);
                if (infoMenu != null)
                {
                    menuId = infoMenu.ID;
                    if (infoMenu.SA > 0)
                    {
                        //
                        string returnUrl;
                        //Xử lý đăng nhập
                        if (!SecurityHelper.IsAuthenticated(out returnUrl))
                        {
                            if (string.IsNullOrEmpty(returnUrl))
                            {
                                
                                Session["returnUrl"] = Configurations.ROOTPATH + HttpContext.Current.Request.RawUrl;
                                VcoinService vcoin = new VcoinService();
                                Response.Redirect(vcoin.StringAuthentication(HttpUtility.UrlEncode(Configurations.ROOTPATH + HttpContext.Current.Request.RawUrl)));
                            }
                            else
                                Response.Redirect(returnUrl);
                        }
                            
                        if (infoPortal.SA > 0)
                        {
                            int isPermission = SecurityHelper.IsDenied(Session.GetUser().USERID, menuId);
                            if (isPermission != menuId)
                            {
                                if (isPermission > 0)
                                    Response.Redirect(Configurations.ROOTDIR + "Default.aspx?p=" + portalId + "&m=" +
                                                      isPermission);
                                else
                                    Response.Redirect(Configurations.ROOTDIR);
                            }
                        }
                    }
                    string basePath = Configurations.ROOTDIR + "Templates/" + infoPortal.LAYOUT;

                    if (!string.IsNullOrEmpty(infoPortal.THEME))
                    {
                        var infoTheme = JsonSerializer.DeserializeFromString<JTheme>(infoPortal.THEME);
                        if (infoTheme != null)
                        {
                            string templatePath = basePath + infoTheme.control;
                            TmpControl = (BaseTemplate)LoadControl(templatePath);
                            Page.Title = "(" + cfg.SiteName.VALUE + ") - " + infoMenu.NAME;
                            RegisterMeta(infoTheme.meta);
                            RegisterCss(infoTheme.css);
                            RegisterJavascript(infoTheme.js);
                            RegisterExeJavascript();

                            if (!string.IsNullOrEmpty(infoPortal.MASTERPAGE))
                            {
                                List<JSection> lstMaster = JsonSerializer.DeserializeFromString<List<JSection>>(infoPortal.MASTERPAGE);
                                if (lstMaster != null)
                                {
                                    if (lstMaster.Count > 0)
                                    {
                                        foreach (var jMaster in lstMaster)
                                        {
                                            if (TmpControl.Containers.ContainsKey(jMaster.placeholder))
                                            {
                                                Control toAdd = LoadControl(jMaster.control, jMaster);
                                                TmpControl.Containers[jMaster.placeholder].Controls.Add(toAdd);
                                            }
                                        }
                                    }
                                }
                                if (!string.IsNullOrEmpty(infoMenu.MENULAYOUT))
                                {
                                    List<JMenuType> lstMenuType = JsonSerializer.DeserializeFromString<List<JMenuType>>(infoMenu.MENULAYOUT);
                                    if (lstMenuType != null)
                                    {
                                        if (lstMenuType.Count > menutypeId)
                                        {
                                            JMenuType infoMenuType = lstMenuType[menutypeId];
                                            if (infoMenuType != null)
                                            {
                                                if (infoMenuType.control != null)
                                                {
                                                    if (infoMenuType.control.Count > 0)
                                                    {
                                                        RegisterCss(infoMenuType.css);
                                                        RegisterJavascript(infoMenuType.js);
                                                        foreach (var section in infoMenuType.control)
                                                        {
                                                            if (TmpControl.Containers.ContainsKey(section.placeholder))
                                                            {
                                                                Control toAdd = LoadControl(section.control, section);
                                                                TmpControl.Containers[section.placeholder].Controls.Add(toAdd);
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                            plContent.Controls.AddAt(0, TmpControl);
                            for (int i = Controls.Count - 1; i < 0; i--)
                                Controls.RemoveAt(i);
                        }
                    }
                }
                else
                    RedirectHelper.ErrorRedirect("Can't load menu !");
            }
            else
                RedirectHelper.ErrorRedirect("Can't load portal !");
        }
    }
}